package client;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class EditWindow extends JFrame {

	private JPanel buttPanel = new JPanel();
	private Button okButt = new Button("Save");
	private Button cancelButt = new Button("Cancel");
	private JTextArea textArea = new JTextArea();
	private JPanel allPanel = new JPanel();

	boolean waitingForAction = true;
	boolean edited = false;

	public EditWindow() {
		allPanel.setLayout(new BoxLayout(allPanel, BoxLayout.Y_AXIS));

		buttPanel.add(cancelButt);
		textArea.setSize(800, 600);
		allPanel.add(textArea);
		allPanel.add(buttPanel);
		this.add(allPanel);
		okButt.addActionListener(new OkListener());
		cancelButt.addActionListener(new CancelListener());
		
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent we) {
				edited = false;
				notifyAction();
			}
		});
	}

	public synchronized String editText(String s) {
		buttPanel.add(okButt);
		textArea.setText(s);
		this.setVisible(true);
		this.setSize(1000, 800);

		while(waitingForAction){
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		this.setVisible(false);

		if (edited) {
			return textArea.getText();
		} else {
			return null;
		}
	}
	
	public synchronized void notifyAction(){
		waitingForAction = false;
		notifyAll();
	}

	class OkListener implements ActionListener {
		public void actionPerformed(ActionEvent arg0) {
			edited = true;
			notifyAction();
		}
	}

	class CancelListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			edited = false;
			notifyAction();
		}

	}
}
